package cn.lzm.bootstrap;

import cn.lzm.RpcApplication;
import cn.lzm.config.RegistryConfig;
import cn.lzm.config.RpcConfig;
import cn.lzm.model.ServiceMetaInfo;
import cn.lzm.model.ServiceRegisterInfo;
import cn.lzm.registry.LocalRegistry;
import cn.lzm.registry.Registry;
import cn.lzm.registry.RegistryFactory;
import cn.lzm.server.tcp.VertxTcpServerV5;

import java.util.List;

/**
 * @author lzm
 * @Date 2024/11/8
 * @description 服务提供者初始化类
 */
public class ProviderBootstrap {

    /**
     * 初始化
     *
     * @param serviceRegisterInfos 注册信息
     */
    public static void init(List<ServiceRegisterInfo<?>> serviceRegisterInfos) {
        // RPC框架初始化
        RpcApplication.init();

        // 全局配置
        RpcConfig rpcConfig = RpcApplication.getRpcConfig();

        for (ServiceRegisterInfo<?> serviceRegisterInfo : serviceRegisterInfos) {
            String serviceName = serviceRegisterInfo.getServiceName();
            // 本地注册
            LocalRegistry.register(serviceName, serviceRegisterInfo.getImplClass());

            // 注册服务到注册中心
            RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
            Registry registry = RegistryFactory.getInstance(registryConfig.getType());
            ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
            serviceMetaInfo.setName(serviceName);
            serviceMetaInfo.setHost(rpcConfig.getServerHost());
            serviceMetaInfo.setPort(rpcConfig.getServerPort());
            try {
                registry.register(serviceMetaInfo);
            } catch (Exception e) {
                throw new RuntimeException(serviceName + "服务注册失败", e);
            }
        }

        // 启动服务器
        VertxTcpServerV5 tcpServer = new VertxTcpServerV5();
        tcpServer.start(rpcConfig.getServerPort());
    }

}
